//
//  XWCommonPickPopupview.swift
//  XiaoweHearingAid
//
//  Created by Riven on 2023/3/15.
//

import UIKit

class XWCommonPickPopupview: AppOverlayerPopupView {

    private lazy var _contentView = XWHACommonPickPopupContentView(pickerViewHeight: contentViewHeight - 48 - 86 - 20)
    override var contentView: UIView {
        _contentView
    }
    
    var completion: ((Int) -> Void)?

    override func addSubViews() {
        super.addSubViews()
        
        _contentView.clickCallback = { [unowned self] aType in
            if aType == .cancel {
                self.hide()
                return
            }
            self.completion?(self._contentView.pickerView.selectedRow(inComponent: 0))
            self.hide()
        }
    }
    
    override func relayoutSubViews() {
        overlayMaskView.frame = bounds
        
        guard let kWindow = UIApplication.appKeyWindow else {
            return
        }
        let cWidth = bounds.width - 32
        let cHeight: CGFloat = contentViewHeight
        contentView.frame = CGRect(x: 16, y: (bounds.size.height - cHeight - kWindow.safeAreaInsets.bottom - 27), width: cWidth, height: cHeight)
    }
    
    func update(pickerItems: [String], sIndex: Int) {
        _contentView.update(pickerItems: pickerItems, sIndex: sIndex)
    }

}

extension XWCommonPickPopupview {
    
    class func showPick(contentViewHeight: Double = 320, pickerItems: [String], sIndex: Int, completion: @escaping (Int) -> Void) {
        let cView = XWCommonPickPopupview(frame: UIScreen.main.bounds, contentViewHeight: contentViewHeight)
        UIApplication.appKeyWindow?.addSubview(cView)
        
        cView.update(pickerItems: pickerItems, sIndex: sIndex)
        cView.completion = completion
        
        cView.show()
    }
    
}
